package com.winter.service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.common.base.Strings;
import com.winter.mapper.CompanyPositionMapper;
import com.winter.mapper.DictEntryMapper;
import com.winter.mapper.FinFavInfoMapper;
import com.winter.mapper.PersonalReleaseMapper;
import com.winter.model.CompanyPosition;
import com.winter.model.DictEntry;
import com.winter.model.vo.check.CheckParam;
import com.winter.util.Constants;
import com.winter.util.Result;
import com.winter.util.ResultCode;
import com.winter.utils.StringUtil;

@Service
public class CompanyPositionService {

    @Autowired
    public CompanyPositionMapper companyPositionMapper;

    @Autowired
    public PersonalReleaseMapper personalReleaseMapper;

    @Autowired
    private FinFavInfoMapper finFavInfoMapper;
    
    @Autowired
    private DictEntryMapper dictEntryMapper;

    /**
     * 查询职场 高端职位列表
     */

    public Result queryPageList(Integer pageNumber, Integer pageSize, Long compId, String timeStart, String timeEnd, String companyIndustry,
                                String companyName, String userNo, Integer dcTime, String key) {
        if (pageNumber == null) {
            pageNumber = Constants.PAGENUMBER;
        }
        if (pageSize == null) {
            pageSize = Constants.PAGESIZE;
        }
        if (dcTime != null) {
            Map<String, Object> map = getTime(dcTime, timeStart, timeEnd);
            timeStart = map.get("timeStart").toString();
            timeEnd = map.get("timeEnd").toString();
        }
        Short open = null;
        if (Strings.isNullOrEmpty(userNo)) {
            open = 1;
        }
        Short auditing = 1;
        String orderBy = "orderBy";
        List<CompanyPosition> finCommentInfo1 = companyPositionMapper.queryPageList(compId, orderBy, timeStart, timeEnd,companyIndustry, companyName, null, open, auditing, key);
        PageHelper.startPage(pageNumber, pageSize, false);
        List<CompanyPosition> finCommentInfo = companyPositionMapper.queryPageList(compId, orderBy, timeStart, timeEnd, companyIndustry, companyName, null, open, auditing, key);
	    if (finCommentInfo.size() > 0) {
	    	for (int i = 0; i < finCommentInfo.size(); i++) {
	        	getTypeName(finCommentInfo.get(i));
			}
	    }
        PageInfo<CompanyPosition> pageInfo = new PageInfo<>(finCommentInfo);
        pageInfo.setTotal(finCommentInfo1.size());
        return Result.success(pageInfo);
    }

    /**
     * \ 根据Id查询职场 高端职位信息
     */
    public Result selectByPrimaryKey(Long id, String createUser) {
        if (id == null) {
            return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "职位id不能为空");
        }
        Short open = null;
        Short auditing = null;
        if (Strings.isNullOrEmpty(createUser)) {
            open = 1;
            auditing = 1;
        }
        List<CompanyPosition> position = companyPositionMapper.selectByPrimaryKey(id, null, open, auditing);
        CompanyPosition companyPosition = null;
        if (position.size() > 0) {
            companyPosition = position.get(0);
            companyPosition.setIsCollect("0");
            companyPosition.setPostCount(companyPositionMapper.selectByCountKey(position.get(0).getCompanyId().longValue(), null, open, auditing));
            if (!Strings.isNullOrEmpty(createUser)) {
                Long aLong = finFavInfoMapper.get(companyPosition.getId(), "8", 1, createUser);
                if (aLong > 0) {
                    companyPosition.setIsCollect("1");
                } else {
                    companyPosition.setIsCollect("0");
                }
            }
            getTypeName(companyPosition);
        }
        return Result.success(companyPosition);
    }

    /**
     * 发布职位
     */
    public Result insert(CompanyPosition record) {
        if (Strings.isNullOrEmpty(record.getCreateUser())) {
            return Result.failure(ResultCode.USER_NOT_LOGGED_IN);
        }
        // 校验参数
        String checkPosition = CheckParam.checkPosition(record);
        if (checkPosition != null) {
            return Result.failure(ResultCode.TRUSTED_USER_EXIST, checkPosition);
        }
        if (!Strings.isNullOrEmpty(record.getUserType())) {
            if (record.getUserType()
                      .equals("0")) {
                return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "权限不足，禁止操作");
            }
            int count = companyPositionMapper.querySumCount(record.getCreateUser(), new Short("1"));
            if (record.getUserType()
                      .equals("1")) {
                if (count >= 5) {
                    return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "权限不足，禁止操作");
                }
            }
            if (record.getUserType()
                      .equals("2")) {
                if (count >= 5) {
                    return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "权限不足，禁止操作");
                }
            }
        }
        record.setOpen("1");
        record.setIsvalid("1");
        record.setAuditing("0");
        record.setCreatetime(new Date());
        try {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy/MM/dd");
            record.setPublishTime(sdf.parse(sdf.format(new Date())));
        } catch (ParseException e) {
            e.printStackTrace();
        }
        record.setUpdatetime(new Date());
        record.setUpdateUser(record.getCreateUser());
        int i = companyPositionMapper.insertSelective(record);
        if (i <= 0) {
            return Result.failure(ResultCode.FAILURE, "发布职业失败");
        }
        return Result.success(record);
    }


    /**
     * 我的信息 应聘的职位列表
     */
    public Result queryPageUserList(Integer pageNumber, Integer pageSize, String userNo, Short jobtype) {
        if (pageNumber == null) {
            pageNumber = Constants.PAGENUMBER;
        }
        if (pageSize == null) {
            pageSize = Constants.PAGESIZE;
        }
        if (Strings.isNullOrEmpty(userNo)) {
            return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "用户账户不能为空");
        }
        if (jobtype == null) {
            return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "求职类型不能为空");
        }
        String companyId = "companyId";
        String orderBy = "c2.publish_time desc";
        Short auditing = 1;
        PageHelper.startPage(pageNumber, pageSize, false);
        List<CompanyPosition> list = companyPositionMapper.queryPageUserList(companyId, orderBy, userNo, null, auditing, jobtype);
        if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				getTypeName(list.get(i));
			}
		}
        PageInfo<CompanyPosition> pageInfo = new PageInfo<>(list);
        return Result.success(pageInfo);
    }

    /**
     * 根据userNo获取已发步的职业
     */
    public Result queryPageJobFunctionList(Integer pageNumber, Integer pageSize, String userNo, String companyLike) {
        if (Strings.isNullOrEmpty(userNo)) {
            return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "用户账户不能为空");
        }
        PageHelper.startPage(pageNumber, pageSize, false);
        String orderBy = "c1.publish_time desc";
        List<CompanyPosition> list = companyPositionMapper.queryPageJobFunctionList(orderBy, userNo, companyLike);
        if (list.size() > 0) {
			for (int i = 0; i < list.size(); i++) {
				getTypeName(list.get(i));
			}
		}
        PageInfo<CompanyPosition> pageInfo = new PageInfo<>(list);
        return Result.success(pageInfo);
    }


    /**
     * 根据职位id删除
     */
    public Result delete(Long id) {
        if (id == null) {
            return Result.failure(ResultCode.FAILURE, "职位Id不能为空");
        }
        int k = companyPositionMapper.deleteByPrimaryKey(id);
        if (k <= 0) {
            return Result.failure(ResultCode.FAILURE, "删除职位失败");
        }
        return Result.success();
    }

    /**
     * 根据职位id修改
     */
    public Result update(CompanyPosition record) {
        if (record.getId() == null) {
            return Result.failure(ResultCode.FAILURE, "职位Id不能为空");
        }

        if (Strings.isNullOrEmpty(record.getUpdateUser())) {
            return Result.failure(ResultCode.FAILURE, "修改人不能为空");
        }
        record.setUpdateUser(record.getUpdateUser());
        record.setUpdatetime(new Date());
        int i = companyPositionMapper.updateByPrimaryKeySelective(record);
        if (i <= 0) {
            return Result.failure(ResultCode.FAILURE, "修改职位失败");
        }
        return Result.success();
    }

    public static Map<String, Object> getTime(Integer dcTime, String timeStart, String timeEnd) {
        SimpleDateFormat format = new SimpleDateFormat("yyyyMMdd");
        if (dcTime == 1) {
            timeStart = format.format(new Date());
            timeEnd = format.format(new Date());
        } else if (dcTime == 2) {
            timeStart = StringUtil.getStatetime(2);
            timeEnd = format.format(new Date());
        } else if (dcTime == 3) {
            timeStart = StringUtil.getStatetime(6);
            timeEnd = format.format(new Date());
        } else if (dcTime == 4) {
            timeStart = StringUtil.getStatetime(29);
            timeEnd = format.format(new Date());
        } else if (dcTime == 5) {
            timeStart = StringUtil.getStatetime(89);
            timeEnd = format.format(new Date());
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map.put("timeStart", timeStart);
        map.put("timeEnd", timeEnd);
        return map;
    }

    /**
     * 查询推荐职位列表
     */
    public Result queryGroomList(Integer pageNumber, Integer pageSize, String jobFunction, String id) {
        if (pageNumber == null) {
            pageNumber = Constants.PAGENUMBER;
        }
        if (pageSize == null) {
            pageSize = Constants.PAGESIZE;
        }
        if (Strings.isNullOrEmpty(jobFunction)) {
            return Result.failure(ResultCode.FAILURE, "职位职能不能为空");
        }
        if (Strings.isNullOrEmpty(id.toString())) {
            return Result.failure(ResultCode.FAILURE, "职位id不能为空");
        }
        PageHelper.startPage(pageNumber, pageSize, false);
        List<Long> ids = new ArrayList<Long>();
    	ids.add(Long.valueOf(id));
        List<CompanyPosition> finCommentInfo = companyPositionMapper.queryGroomList(jobFunction,ids);
        if(finCommentInfo.size() < 3){
        	if(finCommentInfo.size() > 0){
        		for (int i = 0; i < finCommentInfo.size(); i++) {
            		ids.add(finCommentInfo.get(i).getId());
    			}
        	}
        	List<CompanyPosition> groomList = companyPositionMapper.queryGroomList(null,ids);
        	for (int i = 0; i < 4-finCommentInfo.size(); i++) {
        		finCommentInfo.add(groomList.get(i));
			}
        }
        if (finCommentInfo.size() > 0) {
			for (int i = 0; i < finCommentInfo.size(); i++) {
				getTypeName(finCommentInfo.get(i));
			}
		}
        PageInfo<CompanyPosition> pageInfo = new PageInfo<>(finCommentInfo);
        return Result.success(pageInfo);
    }

    /**
     * 查询已发布的职位列表
     */
    public Result queryPoistListBy(Integer pageNumber, Integer pageSize, String userNo) {
        if (pageNumber == null) {
            pageNumber = Constants.PAGENUMBER;
        }
        if (pageSize == null) {
            pageSize = Constants.PAGESIZE;
        }
        if (Strings.isNullOrEmpty(userNo)) {
            return Result.failure(ResultCode.SYSTEM_UNAUTHORIZED, "用户账号不能为空");
        }
        PageHelper.startPage(pageNumber, pageSize, false);
        List<CompanyPosition> position = companyPositionMapper.selectByPrimaryKey(null, userNo, null, null);
        if (position.size() > 0) {
			for (int i = 0; i < position.size(); i++) {
				getTypeName(position.get(i));
			}
		}
        PageInfo<CompanyPosition> pageInfo = new PageInfo<>(position);
        return Result.success(pageInfo);
    }
    
    public void getTypeName(CompanyPosition position) {
        DictEntry dictEntry = dictEntryMapper.get("DC_INDU_CLASSIFY", position.getCompanyIndustry());
        if (dictEntry != null) {
        	position.setCompanyIndustry(dictEntry.getDictname());
        }
    }

}
